import _imports  # 只在此项目有效，其他项目，请去掉此 import
import pybi as pbi
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Boxplot
import random
from pyecharts.charts import HeatMap
from pyecharts.faker import Faker

pbi.add_markdown("# pyecharts 使用")

tabs = pbi.add_tabs(["热力图", "使用dataset", "设置jsCode", "Boxplot"])


with tabs["使用dataset"]:
    pbi.add_markdown("# Dataset normal bar example")
    pbi.add_markdown(
        "[点这里，查看 pyecharts 示例](https://gallery.pyecharts.org/#/Dataset/dataset_bar_1)"
    )

    pbi.add_markdown("---")

    df = pd.DataFrame(
        [
            [89.3, 58212, "Matcha Latte"],
            [57.1, 78254, "Milk Tea"],
            [74.4, 41032, "Cheese Cocoa"],
            [50.1, 12755, "Cheese Brownie"],
            [89.7, 20145, "Matcha Cocoa"],
            [68.1, 79146, "Tea"],
            [19.6, 91852, "Orange Juice"],
            [10.6, 101852, "Lemon Juice"],
            [32.7, 20112, "Walnut Brownie"],
        ],
        columns=["score", "amount", "product"],
    )

    data = pbi.set_source(df)

    query = pbi.sql(f"select * from {data}").toflatlist(with_header=True)

    c = (
        Bar()
        .add_dataset(source=query)
        .add_yaxis(
            series_name="",
            y_axis=[],
            encode={"x": "amount", "y": "product"},
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Dataset normal bar example"),
            xaxis_opts=opts.AxisOpts(name="amount"),
            yaxis_opts=opts.AxisOpts(type_="category"),
            visualmap_opts=opts.VisualMapOpts(
                orient="horizontal",
                pos_left="center",
                min_=10,
                max_=100,
                range_text=["High Score", "Low Score"],
                dimension=0,
                range_color=["#D7DA8B", "#E15457"],
            ),
        )
    )

    pbi.add_slicer(data["product"])

    pbi.add_text("这是动态生成的图表数据")
    pbi.add_text(query)

    # set_debugTag 可以在页面查看图表配置数据
    pbi.add_echart(c).set_debugTag("xx").set_height("30em")


with tabs["设置jsCode"]:
    pbi.add_markdown("# 支持 pyecharts 中的设置 js 代码")
    pbi.add_markdown(
        "[点这里，查看 pyecharts 示例](https://gallery.pyecharts.org/#/Bar/stack_bar_percent)"
    )

    pbi.add_markdown("目前不支持 pyecharts 的主题设置")
    pbi.add_markdown("---")

    list2 = [
        {"value": 12, "percent": 12 / (12 + 3), "cat": "A"},
        {"value": 23, "percent": 23 / (23 + 21), "cat": "A"},
        {"value": 33, "percent": 33 / (33 + 5), "cat": "A"},
        {"value": 3, "percent": 3 / (3 + 52), "cat": "A"},
        {"value": 33, "percent": 33 / (33 + 43), "cat": "A"},
    ]

    list3 = [
        {"value": 3, "percent": 3 / (12 + 3), "cat": "B"},
        {"value": 21, "percent": 21 / (23 + 21), "cat": "B"},
        {"value": 5, "percent": 5 / (33 + 5), "cat": "B"},
        {"value": 52, "percent": 52 / (3 + 52), "cat": "B"},
        {"value": 43, "percent": 43 / (33 + 43), "cat": "B"},
    ]

    df = pd.DataFrame(list2 + list3)
    data = pbi.set_source(df)
    query = pbi.sql(f"select * from {data}")

    c = (
        Bar()
        .add_xaxis([1, 2, 3, 4, 5])
        .add_yaxis(
            "product1",
            pbi.sql(f'select * from {data} where cat="A"'),
            stack="stack1",
            category_gap="50%",
        )
        .add_yaxis(
            "product2",
            pbi.sql(f'select * from {data} where cat="B"'),
            stack="stack1",
            category_gap="50%",
        )
        .set_series_opts(
            label_opts=opts.LabelOpts(
                position="right",
                formatter=JsCode(
                    "function(x){return Number(x.data.percent * 100).toFixed() + '%';}"
                ),
            )
        )
    )
    pbi.add_slicer(data["cat"])

    pbi.add_echart(c).set_height("30em")


with tabs["Boxplot"]:
    pbi.add_markdown("# Boxplot - Boxplot_base")
    pbi.add_markdown(
        "[点这里，查看 pyecharts 示例](https://gallery.pyecharts.org/#/Boxplot/boxplot_base)"
    )

    pbi.add_markdown("---")

    v1 = [
        [850, 740, 900, 1070, 930, 850, 950, 980, 980, 880, 1000, 980],
        [960, 940, 960, 940, 880, 800, 850, 880, 900, 840, 830, 790],
    ]
    v2 = [
        [890, 810, 810, 820, 800, 770, 760, 740, 750, 760, 910, 920],
        [890, 840, 780, 810, 760, 810, 790, 810, 820, 850, 870, 870],
    ]
    c = Boxplot()

    v1 = c.prepare_data(v1)
    v2 = c.prepare_data(v2)

    df = pd.DataFrame(v1 + v2, columns=["min", "Q1", "median", "Q3", "max"])
    df.loc[:2, "cat"] = "A"
    df.loc[2:, "cat"] = "B"

    data = pbi.set_source(df)
    query_a = pbi.sql(f'select * from {data} where cat="A"')
    query_b = pbi.sql(f'select * from {data} where cat="B"')

    c.add_xaxis(["expr1", "expr2"])
    c.add_yaxis("A", query_a.toflatlist())
    c.add_yaxis("B", query_b.toflatlist())
    c.set_global_opts(title_opts=opts.TitleOpts(title="BoxPlot-基本示例"))

    pbi.add_slicer(data["cat"])
    pbi.add_echart(c).set_height("30em")


with tabs["热力图"]:
    pbi.add_markdown("# Heatmap - `Heatmap_with_label_show`")
    pbi.add_markdown(
        "[点这里，查看 pyecharts 示例](https://gallery.pyecharts.org/#/Heatmap/heatmap_with_label_show)"
    )

    pbi.add_markdown("---")

    value = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]

    df = pd.DataFrame(value, columns=["i", "j", "k"])

    df["week"] = Faker.week * 24
    df["clock"] = Faker.clock * 7

    data = pbi.set_source(df)

    # 避免切片器影响 data。因为我们希望保持热力图的x和y轴不变化
    data_week = pbi.set_source(pd.DataFrame({"week": Faker.week}))
    data_clock = pbi.set_source(pd.DataFrame({"clock": Faker.clock}))

    c = (
        HeatMap()
        .add_xaxis(pbi.sql(f"select clock from {data_clock}"))
        .add_yaxis(
            "series0",
            pbi.sql(f"select week from {data_week}"),
            pbi.sql(f"select i,j,k from {data}").toflatlist(),
            label_opts=opts.LabelOpts(is_show=True, position="inside"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="HeatMap-Label 显示"),
            visualmap_opts=opts.VisualMapOpts(),
        )
    )

    pbi.add_slicer(data["week"])
    pbi.add_slicer(data["clock"])

    pbi.add_echart(c).set_height("30em")


pbi.to_html("test.html")
